package com.example.mybatisplustenantdemo.config;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import com.example.mybatisplustenantdemo.constants.Global;
import com.example.mybatisplustenantdemo.properties.TenantProperties;
import com.example.mybatisplustenantdemo.util.LoginUserUtils;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.ArrayList;

/**
 * MybatsPlus配置类
 * Created by dell on 2019/1/10.
 * @author dell
 */
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {

    private static final Logger LOG = LoggerFactory.getLogger(MybatisPlusConfig.class);

    @Autowired
    private TenantProperties tenantProperties;

    public static final char SYMBOL = '`';

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        PaginationInterceptor page = new PaginationInterceptor();
        //设置方言类型
        page.setDialectType("mysql");
        if(tenantProperties.isEnabledTenant()){
            initTenantHandler(page);
            LOG.debug("===============================多租户管理器已开启======================================");
        }
        return page;
    }

    /**
     * 初始化多租户处理器
     * @param paginationInterceptor
     */
    public void initTenantHandler(PaginationInterceptor paginationInterceptor){
        ArrayList<ISqlParser> sqlParsers = new ArrayList<>();
        TenantSqlParser tenantSqlParser = new TenantSqlParserExt();
        tenantSqlParser.setTenantHandler(new TenantHandler() {
            @Override
            public Expression getTenantId(boolean where) {
                return new LongValue(LoginUserUtils.getTenantId());
            }

            @Override
            public String getTenantIdColumn() {
                return Global.TENANT_ID_COLUMN;
            }

            @Override
            public boolean doTableFilter(String tableName) {
                tableName = clearSymbol(tableName);
                boolean is = tenantProperties.getNotTenantIdTable().contains(tableName.toLowerCase());
                return is;
            }
        });
        sqlParsers.add(tenantSqlParser);
        paginationInterceptor.setSqlParserList(sqlParsers);
    }

    /**
     * 清楚表中的转义符号
     * @param tableName
     * @return
     */
    private String clearSymbol(String tableName){
        char[] chars = tableName.toCharArray();
        if(chars[0] == SYMBOL){
            return tableName.substring(1, tableName.length() - 1);
        }
        return tableName;
    }

    /**
     * 乐观锁 插件
     * @return
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLoker() {
        return new OptimisticLockerInterceptor();
    }

}
